﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Threading;

namespace CheckFreeWayServer
{
    class ServidorSocket
    {
        int _port;
        bool _mantemRodando;
        TcpListener sckServer;

        public ServidorSocket(int port)
        {
            try
            {
                _port = port;
                sckServer = new TcpListener(port);
                sckServer.Start(100);
                _mantemRodando = true;
            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog.WriteEntry(ex.Source, ex.StackTrace, System.Diagnostics.EventLogEntryType.Error,7701);
                System.Diagnostics.EventLog.WriteEntry(ex.Source, "Erro ao dar Listen na porta: " + _port.ToString(), System.Diagnostics.EventLogEntryType.Error, 7701);
            }
        }

        public void Run()
        {
            while (_mantemRodando)
            {
                try
                {
                    Socket sckClient = sckServer.AcceptSocket();
                    if (sckClient != null)
                    {
                        TrataConexaoSocketClient tcsc = new TrataConexaoSocketClient(sckClient, _port);
                        Thread thr = new Thread(new ThreadStart(tcsc.Run));
                        thr.Start();
                    }
                }
                catch (Exception ex)
                {
                    if (_mantemRodando) // Se o erro for por STOP no StopRun - Não loga no EventViewer
                    {
                        System.Diagnostics.EventLog.WriteEntry(ex.Source, ex.StackTrace, System.Diagnostics.EventLogEntryType.Error, 7702);
                        System.Diagnostics.EventLog.WriteEntry(ex.Source, "Erro ao dar Accept na porta: " + _port.ToString(), System.Diagnostics.EventLogEntryType.Error, 7702);
                    }
                }
            }
        }

        public void StopRun()
        {
            _mantemRodando = false;
            sckServer.Stop();
        }
    }
}
